package top.xiaoazi.futureletterserver.module.letter.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import top.xiaoazi.futureletterserver.module.letter.vo.LetterSentVO;
import top.xiaoazi.futureletterserver.utils.EmailUtils;

@Slf4j
public class LetterEmailUtils extends EmailUtils {
    private final JavaMailSender mailSender;
    private final String from = "zlcode.top@foxmail.com";// 发件人
    {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(HOST);
        javaMailSender.setPort(PORT);
        javaMailSender.setUsername(USERNAME);
        javaMailSender.setPassword(PASSWORD);
        javaMailSender.setProtocol("smtps");
        javaMailSender.setDefaultEncoding("utf8");
        this.mailSender = javaMailSender;
    }

    public String getTemplate(LetterSentVO letter) {
        return """
                <body>
                    <style>
                        .gap {
                            border-bottom: 1px solid #dcdfe6;
                            margin-bottom: 30px;
                        }
                        .bottom {
                            color: #a7a7a8;
                            font-size: 14px;
                        }
                    </style>

                    <div>
                        %s
                    </div>
                    <div class="gap"></div>
                    <p class="bottom">(该邮件由ZLCode用户：<b> %s </b> 委托 ”ZLCode给未来写封信模块“发出, 委托人邮箱：<b> %s </b>, 请勿直接回复.)</p>
                </body>
                """.formatted(letter.getContent(), letter.getUsername(), letter.getEmail());
    }

    public boolean send(LetterSentVO letter) {
        // 创建一个邮件消息
        MimeMessage message = mailSender.createMimeMessage();

        // 创建 MimeMessageHelper
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, false);
            // 发件人邮箱和名称
            helper.setFrom(from);
            // 收件人邮箱
            helper.setTo(letter.getToEmail());
            // 邮件标题
            helper.setSubject(letter.getTitle());
            // 邮件正文，第二个参数表示是否是HTML正文
            String content = getTemplate(letter);
            helper.setText(content, true);
            // 发送
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("LetterEmailUtils 发送邮箱失败" + e);
            return false;
        }
        return true;
    }
}
